import React, { useEffect, useState, useCallback, useRef } from 'react'
import BScroll from 'better-scroll'
import { ScrollWrapper } from './styledScroll'
import { useDispatch } from 'react-redux'

export default function Scroll({children, id, loadDataSaga, list}) {
  const scroll = useRef(null)
  const firstLoad = useRef(true)
  let [currentPage, setCurrentPage] = useState(1)
  let [isPullUpLoad, setIsPullUpload] = useState(false)
  let dispatch = useDispatch()

  useEffect(() => {
    if (!firstLoad.current) {
      scroll.current.finishPullUp()
      // 在refresh()之前做，因为要回到上一次过拽的内容高度的位置
      scroll.current.scrollTo(0, scroll.current.maxScrollY + 150)
      scroll.current.refresh()
      setIsPullUpload(false)
    }
  }, [list, scroll])

  const pullingUpHandler = useCallback(
    async () => {
      firstLoad.current = false
      setCurrentPage(currentPage+1)
      setIsPullUpload(true)

      dispatch(loadDataSaga((currentPage+1) * 5))
    },
    [dispatch, currentPage, loadDataSaga],
  )

  useEffect(() => {
    scroll.current = new BScroll(`#${id}`, {
      pullUpLoad: true,
      click: true
    })
    
    scroll.current.on('pullingUp', pullingUpHandler)
    
  }, [scroll, pullingUpHandler, id])

  useEffect(() => {
    (async () => {
      // 异步函数可以直接await，会等待异步调用完成
      await dispatch(loadDataSaga(5))
      scroll.current.refresh()
    })()
  }, [dispatch, scroll, loadDataSaga])

  return (
    <>
      <ScrollWrapper id={id}>
        <div className="container">
          <div>{children}</div>
          <div className="pullup-tips">
            {
              !isPullUpLoad
                ? (
                  <div className="before-trigger">
                    <span className="pullup-txt">Pull up and load more</span>
                  </div>
                ) : (
                  <div className="after-trigger">
                    <span className="pullup-txt">Loading...</span>
                  </div>
                )
            }
          </div>
        </div>
      </ScrollWrapper>
    </>
  )
}